package com.tony.juc.ThreadPool;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: NewFixedThreadPoolDemo002
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/17/19:43
 * @Description: Callable实现NewFixedThreadPool
 */
public class NewFixedThreadPoolDemo002 {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2); //创建2个大小线程池
        //在集合里面存放所有要执行的线程的任务对象，而这个对象为Callable实现
        Set<Callable<String>> allThreads = new HashSet<>(); //线程绑定
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            allThreads.add(()->{
                return String.format("【%s】皮蛋布丁任务的处理结果：num = %d",Thread.currentThread().getName(),temp);
            }); //再加入线程集合
        }
        //经过如上对的处理之后，所有的线程任务已经添加完成了，那么随后就要执行这些任务
        List<Future<String>> results = service.invokeAll(allThreads);//执行任务
        results.forEach((future)->{
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
